﻿
//======================================================================================================================
//USAGE NOTES
//This script module should be put on each CALLING PAGE - i.e. on the HTML of those calling pages put something like:
//      <script type="text/javascript" src="@(Url.Content("~"))Scripts/Trintech.JERoutingDistributable.js"></script>
//All Calling pages should implement:
//  1.  Naming the popup dialog as follows:   $('#RoutingDialog').dialog('open');
//  2.  Having this field:     @Html.Hidden("JERoutingCallingPageShouldRefresh", new { id = "JERoutingCallingPageShouldRefresh" })
//  3.  Having this function to handle what happens after dialog closes.   Example:
//         function JERoutingDialogPostCloseProcessingUniqueToCallingPage() {
//              var jeRoutingDialogRecommendedRefresh = $('#JERoutingCallingPageShouldRefresh').val();
//              if (jeRoutingDialogRecommendedRefresh == "true") {
//                   JERefreshPrepPage(); //it is possible that your permissions changed on the JE etc
//              }
//         }
//
//======================================================================================================================


function JERoutingReady() {
    //to be called by page ready function
    JERoutingInitialPageSetup();
}

function JERoutingRegisterPageLoadEvents() {
    //placeholder for now.  Do a solutionwide find to see what calls this from calling pages.
}

function JERoutingInitialPageSetup() {
    JERoutingRegisterButtonsAndOtherEvents();
    //JERoutingRegisterValidationFields();  //Generated with page
    //JERoutingCheckStartupMessages();
    JERoutingDisableInitialControlsAsNeeded();
    JERoutingShowPageLevelErrorMessage();
}

function JERoutingRegisterButtonsAndOtherEvents() {
    $('#ApproverRoutingModalSaveButton').click(function () { JERoutingSaveClicked(); });
    $('#ApproverRoutingModalCancelButton').click(function () { JERoutingCancelClicked(); });

    //Event handlers for changing checkbox
    $('#CustomizeCheckbox').click(function () { JERoutingCustomizeCheckboxClicked(); });

    //Event handlers for changing dropdowns
    $('#GuidStringOfApproverSequence').change(function () {
        JERoutingChangedApproverSequence();
    });

    $('#GuidStringOfPreparer').change(function () {
        JERoutingChangedPreparer();
    });
}


/**** GENERAL UTILITIES ==================================================================================== ****/

function JERoutingShowPageLevelErrorMessage() {
    //only shows a message if there is one
    var pageLevelError = $('#PageLevelErrorMessage').val();
    if (pageLevelError != '') {
        $('#JERoutingPageMsg').show();   //any special treatment if the message is a general error?
        $('#JERoutingPageMsg').html(pageLevelError);
    }
}

function JERoutingResetPageMessage() {
    $('#JERoutingPageMsg').hide();
    $('#JERoutingPageMsg').html('');
}

function JERoutingResetValidationErrors() {
    $('.JEValidatable').removeClass("input-validation-error");
}

function JERoutingHighlightFieldErrors(errorDictionary) {
    //This code is under construction, it has not been completed yet.
    $('#JERoutingForm').validate().showErrors(errorDictionary);
    //    for (var key in errorDictionary) {
    //        $('#' + key).addClass("input-validation-error");
    //        //Set spans with error msgs to 'field-validation-error'
    //    }
}

function JERoutingDialogClose() {
    //IMPORTANT:  Every calling page should name this dialog the same (it should be the title of a div on the calling page) 
    $('#RoutingDialog').dialog('close');
    JERoutingDialogPostCloseProcessingUniqueToCallingPage(); //Calling pages may have unique operations to do after closes.  They need to implement this function.
}

function JERoutingRefreshPage() {
    var jeId = $('#JEGuid').val();
    var cameFrom = $('#WhoCalledThisPage').val();
    var packet = { jeId: jeId, cameFrom: cameFrom };

    $.ajax({
        type: "get",
        url: $('#JERoutingRefreshPageURL').val(),
        data: packet,
        success: JERoutingRefreshPageSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });
}

function JERoutingRefreshPageSuccess(packet) {
    $('#RoutingDialog').html(packet);
    //JERoutingInitialPageSetup();  //do not need to do this at this time, page ready on the refresh does it
}


/**** AJAX GENERAL RESPONSE HANDLING ============================================================================= ****/

function JERoutingAjaxGeneralSuccess(packet, textStatus, jqXHR) {

    //Expects packet to be a JERoutingAjaxGeneralResponse object.  
    //JERoutingAjaxGeneralResponse was defined in JERoutingController as of this writing.

    if (packet.HasFieldErrors) {
        JERoutingHighlightFieldErrors(packet.FieldErrorList);   
        //return; //we may not want to return here, you can possibly have field errors and other messages as well.
    }

    if (packet.HasPopupMessage) {
        var popupTitle = "";
        if (packet.HasPopupErrors) {
            popupTitle = packet.PopupErrorTitleGeneric;
        }
        OpenMessageDialog(packet.FormattedPopupMessage, popupTitle);
        return;
    }

    if (packet.HasPageMsg) {
        $('#JERoutingPageMsg').show();   //any special treatment if the message is a general error?
        $('#JERoutingPageMsg').html(packet.PageMsg);
    }

    if (packet.HasErrors) {
        return;
    }

    //Will NOT go to dashboard directly from the popup.  Will let calling pages decide if they need to do that.
    //    //Old notes and code:
    //    //Note that you may not want to go to dashboard if you had errors on the current page.  We can talk this out later, or just leave to developer to set the flags correctly.
    //    if (packet.GoToDashboard) {
    //        //JERoutingDialogClose(); ???
    //        window.location = $('#JEPrepDashboardURL').val();
    //        return;
    //    }

    if (packet.ButtonOrActionName == "save") {
        $('#JERoutingCallingPageShouldRefresh').val('True');
        JERoutingDialogClose();   //Close dialog and return to calling page.
        //JERoutingDialogPostSaveProcessingUniqueToCallingPage(); //Calling pages may have unique operations to do after saves.  They need to implement this function.
    }

}


/**** BUTTON CLICKS ==================================================================================== ****/

function JERoutingSaveClicked() {

    JERoutingResetPageMessage();
    JERoutingResetValidationErrors();

    //Trigger page validation first
    var isValid = $('#JERoutingForm').validate().form();  //var isValid = $('#JERoutingForm').validate().valid();
    if (!isValid) {
        return;
    }

    //We could serialize here but it has 2 disadvantages - serialize uses NAME vs id, and also does not pick up disabled fields.
    //There are workarounds to both issues, but if the number of data pieces is fairly small, just send them over in a packet.
    //At this time, if you serialize, it will not collect disabled fields unless you do the following
    //    var disabled = $('#JERoutingForm').find(':input:disabled').removeAttr('disabled');
    //    var formData = $('#JERoutingForm').serialize();
    //    disabled.attr('disabled', 'disabled');

    var jeId = $('#JEGuid').val();
    var whoCalledThisPage = $('#WhoCalledThisPage').val(); 
    var customizeCheckbox = $('#CustomizeCheckbox').is(":checked");
    var guidStringOfApproverSequence = $('#GuidStringOfApproverSequence').val();
    var guidStringOfPreparer = $('#GuidStringOfPreparer').val();
    var guidStringOfApprover1 = $('#GuidStringOfApprover1').val();
    var guidStringOfApprover2 = $('#GuidStringOfApprover2').val();
    var guidStringOfApprover3 = $('#GuidStringOfApprover3').val();
    var guidStringOfApprover4 = $('#GuidStringOfApprover4').val();
    var guidStringOfApprover5 = $('#GuidStringOfApprover5').val();
    var guidStringOfApprover6 = $('#GuidStringOfApprover6').val();

    var packet = {
        jeId: jeId,
        whoCalledThisPage: whoCalledThisPage,
        customizeCheckbox: customizeCheckbox,
        guidStringOfApproverSequence: guidStringOfApproverSequence,
        guidStringOfPreparer: guidStringOfPreparer,
        guidStringOfApprover1: guidStringOfApprover1,
        guidStringOfApprover2: guidStringOfApprover2,
        guidStringOfApprover3: guidStringOfApprover3,
        guidStringOfApprover4: guidStringOfApprover4,
        guidStringOfApprover5: guidStringOfApprover5,
        guidStringOfApprover6: guidStringOfApprover6
    };
    
    $.ajax({
        type: "post",
        url: $('#JERoutingSaveURL').val(),
        data: packet,  //formData
        success: JERoutingAjaxGeneralSuccess,
        error: DisplayTrintechAjaxError,
        cache: false
    });

}


function JERoutingCancelClicked() {
    JERoutingDialogClose();
}


function JERoutingCustomizeCheckboxClicked() {

    if ($('#CustomizeCheckbox').is(":checked")) {
        JERoutingCustomizeTurnOn();
    }
    else {
        //Customize is UNchecked.
        var jeId = $('#JEGuid').val();
        var packet = { jeId: jeId };

        $.ajax({
            type: "post",
            url: $('#JERoutingRunRoutingRulesIfNeededURL').val(),
            data: packet,
            datatype: 'json',
            success: JERoutingRunRoutingRulesIfNeededSuccess,
            error: DisplayTrintechAjaxError,
            async: false,
            cache: false
        });

    }
}

function JERoutingCustomizeTurnOn() {

    //Customize IS checked.
    //   DISABLE approver sequence dropdown.  
    //   Enable all approver dropdowns IF they should be enabled (i.e. are not complete, etc.)
    //   Use our existing completeness flags to make this decision.   

    $('#GuidStringOfApproverSequence').attr('disabled', 'disabled');

    if ($('#IsCompleteApprover1').val() == "False") {
        $('#GuidStringOfApprover1').removeAttr('disabled');
    }
    if ($('#IsCompleteApprover2').val() == "False") {
        $('#GuidStringOfApprover2').removeAttr('disabled');
    }
    if ($('#IsCompleteApprover3').val() == "False") {
        $('#GuidStringOfApprover3').removeAttr('disabled');
    }
    if ($('#IsCompleteApprover4').val() == "False") {
        $('#GuidStringOfApprover4').removeAttr('disabled');
    }
    if ($('#IsCompleteApprover5').val() == "False") {
        $('#GuidStringOfApprover5').removeAttr('disabled');
    }
    if ($('#IsCompleteApprover6').val() == "False") {
        $('#GuidStringOfApprover6').removeAttr('disabled');
    }
}

function JERoutingRunRoutingRulesIfNeededSuccess(packet) {
    
    if (packet.hasError) {
        $('#JERoutingPageMsg').show();
        $('#JERoutingPageMsg').html(packet.errorString);
        return;
    }

    $('#JERoutingCallingPageShouldRefresh').val('True');  //this is a type of SAVE, so tell calling page it will need to refresh when dialog closes

    JERoutingRefreshPage(); //show the updated JE
}

function JERoutingChangedApproverSequence() {
    JERoutingResetPageMessage();
    JERoutingResetValidationErrors();
    JERoutingRefreshApproverSequence();
}

function JERoutingRefreshApproverSequence() {

    //WHAT THIS FUNCTION DOES:
    //    Does not rebuild contents of the individual approver lists.
    //    Simply changes the SELECTED approver in each EXISTING list, based on the approver sequence chosen.
    //    Also accounts for condition where NO approver sequence is chosen (sets each approver dropdown to NONE)

    var jeId = $('#JEGuid').val();
    var selectedApproverSequence = $('#GuidStringOfApproverSequence').val();
    var packet = {
        jeId: jeId,
        selectedApproverSequence: selectedApproverSequence
    };

    $.ajax({
        type: "post",
        url: $('#JERoutingGetApproversForApproverSequenceURL').val(),
        data: packet,
        datatype: 'json',
        success: JERoutingChangedApproverSequenceSuccess,
        error: DisplayTrintechAjaxError,
        async: false,
        cache: false
    });
}

function JERoutingChangedApproverSequenceSuccess(packet, textStatus, jqXHR) {

    if (packet.hasError) {
        $('#JERoutingPageMsg').show();   //any special treatment if the message is a general error?
        $('#JERoutingPageMsg').html(packet.errorString);
        return;
    }

    if (packet.hasErrorButContinue) {
        $('#JERoutingPageMsg').show();   //any special treatment if the message is a general error?
        $('#JERoutingPageMsg').html(packet.errorString);
        //OpenMessageDialog(packet.errorString);
    }

    $('#GuidStringOfApprover1').val(packet.approver1guidStringOrEmptyString);
    $('#GuidStringOfApprover2').val(packet.approver2guidStringOrEmptyString);
    $('#GuidStringOfApprover3').val(packet.approver3guidStringOrEmptyString);
    $('#GuidStringOfApprover4').val(packet.approver4guidStringOrEmptyString);
    $('#GuidStringOfApprover5').val(packet.approver5guidStringOrEmptyString);
    $('#GuidStringOfApprover6').val(packet.approver6guidStringOrEmptyString);

}


function JERoutingChangedPreparer() {

    var selectedPreparer = $('#GuidStringOfPreparer').val();
    var selectedApproverSequence = $('#GuidStringOfApproverSequence').val();
    var jeId = $('#JEGuid').val();
    var packet = { jeId: jeId, selectedPreparer: selectedPreparer, selectedApproverSequence: selectedApproverSequence };

    $.ajax({
        type: "post",
        url: $('#JERoutingGetApproverSequencesForPreparerURL').val(),
        data: packet,
        datatype: 'json',
        success: JERoutingChangedPreparerSuccess,
        error: DisplayTrintechAjaxError,
        async: false,
        cache: false
    });
}


function JERoutingChangedPreparerSuccess(packet, textStatus, jqXHR) {

    //Errors should be handled first and return without altering existing UI components
    if (packet.hasError) {
        OpenMessageDialog(packet.errorString);
        return;
    }

    //TO HANDLE THE PREPARER CHANGE:
    //Fill approver sequence dropdown with the approver sequences new preparer can see.
    //if no approver sequence had been selected
    //      leave existing approvers alone (there may or may not be any due to customize flag), and do NOT turn on CUSTOMIZED.
    //if the new preparer CAN see the currently selected approver sequence
    //      leave existing approvers alone (there may or may not be any due to customize flag), and do NOT turn on CUSTOMIZED.
    //if approver sequence had been selected and new preparer can NOT see it:
    //      leave existing approvers alone, and DO turn on CUSTOMIZED.
    //      when CUSTOMIZED is turned on, the rest of the popup should react accordingly (disable routing dropdown, enable/disable approver dropdowns as needed, etc.)

    //Rebuild approver sequence list in accordance with the new preparer
    $('#GuidStringOfApproverSequence').empty();

    var allStuff = packet.allStuff;
    var selectedStuff = packet.selectedStuff;

    jQuery.each(allStuff, function (index, item) {
        jQuery.each(selectedStuff, function (index2, aSelectedItem) {
            if (item.Value == aSelectedItem.Value) {
                $('#GuidStringOfApproverSequence').append('<option selected="selected" value="' + item.Key + '">' + item.Value + '</option>');
            }
            else {
                $('#GuidStringOfApproverSequence').append('<option value="' + item.Key + '">' + item.Value + '</option>');
            }
        });
    });

    //Turn on customize checkbox as needed
    if (packet.turnOnCustomize) {
        JERoutingResetPageMessage();  //this situation means routing will be turned off but names from it will remain.
        //JERoutingResetValidationErrors();  //remember that names will remain
        $('#CustomizeCheckbox').attr('checked', true);
        //.prop('checked', true) says jquery 1.6 or later but is not working.  having to use .attr('checked', true) to make it work
        JERoutingCustomizeTurnOn();
        OpenMessageDialog(packet.turnOnCustomizeMessage);  //Special situation so we give it a message
    }

    if (packet.clearOutApprovers) {
        clearOutApproverSequenceAndApprovers(packet.turnOnCustomizeMessage);
    }

}

function clearOutApproverSequenceAndApprovers(message) {
    $('#approverSequenceGuidString').val(0);
    $('#GuidStringOfApprover1')[0].selectedIndex = 0;
    $('#GuidStringOfApprover2')[0].selectedIndex = 0;
    $('#GuidStringOfApprover3')[0].selectedIndex = 0;
    $('#GuidStringOfApprover4')[0].selectedIndex = 0;
    $('#GuidStringOfApprover5')[0].selectedIndex = 0;
    $('#GuidStringOfApprover6')[0].selectedIndex = 0;
    OpenMessageDialog(message);  //Special situation so we give it a message
}



/**** ENABLING AND DISABLING ==================================================================================== ****/

function JERoutingDisableInitialControlsAsNeeded() {

    var loc_IsReadOnly = $('#IsRoutingReadOnly').val();
    var loc_ShouldDisableCustomizeCheckbox = $('#ShouldDisableCustomizeCheckbox').val();
    var loc_ShouldDisableApproverSequence = $('#ShouldDisableApproverSequence').val();
    var loc_ShouldDisablePreparer = $('#ShouldDisablePreparer').val();
    var loc_ShouldDisableApprover1 = $('#ShouldDisableApprover1').val();
    var loc_ShouldDisableApprover2 = $('#ShouldDisableApprover2').val();
    var loc_ShouldDisableApprover3 = $('#ShouldDisableApprover3').val();
    var loc_ShouldDisableApprover4 = $('#ShouldDisableApprover4').val();
    var loc_ShouldDisableApprover5 = $('#ShouldDisableApprover5').val();
    var loc_ShouldDisableApprover6 = $('#ShouldDisableApprover6').val();

    if (loc_IsReadOnly == "True") {
        JERoutingSetupReadOnly();
        return;
    }
    else {
        //If not readonly, then start with all parts enabled then turn off parts as needed
        JERoutingEnableAllControls();

        if (loc_ShouldDisableCustomizeCheckbox == "True") {
            $('#CustomizeCheckbox').attr('disabled', 'disabled');
        }

        if (loc_ShouldDisableApproverSequence == "True") {
            $('#GuidStringOfApproverSequence').attr('disabled', 'disabled');
        }

        if (loc_ShouldDisablePreparer == "True") {
            $('#GuidStringOfPreparer').attr('disabled', 'disabled');
        }

        if (loc_ShouldDisableApprover1 == "True") {
            $('#GuidStringOfApprover1').attr('disabled', 'disabled');
        }
        if (loc_ShouldDisableApprover2 == "True") {
            $('#GuidStringOfApprover2').attr('disabled', 'disabled');
        }
        if (loc_ShouldDisableApprover3 == "True") {
            $('#GuidStringOfApprover3').attr('disabled', 'disabled');
        }
        if (loc_ShouldDisableApprover4 == "True") {
            $('#GuidStringOfApprover4').attr('disabled', 'disabled');
        }
        if (loc_ShouldDisableApprover5 == "True") {
            $('#GuidStringOfApprover5').attr('disabled', 'disabled');
        }
        if (loc_ShouldDisableApprover6 == "True") {
            $('#GuidStringOfApprover6').attr('disabled', 'disabled');
        }
    }

}


function JERoutingSetupReadOnly() {
    //$('#JERoutingSaveButton').hide();
    $('#CustomizeCheckbox').attr('disabled', 'disabled');
    $('#GuidStringOfApproverSequence').attr('disabled', 'disabled');
    $('#GuidStringOfPreparer').attr('disabled', 'disabled');
    $('#GuidStringOfApprover1').attr('disabled', 'disabled');
    $('#GuidStringOfApprover2').attr('disabled', 'disabled');
    $('#GuidStringOfApprover3').attr('disabled', 'disabled');
    $('#GuidStringOfApprover4').attr('disabled', 'disabled');
    $('#GuidStringOfApprover5').attr('disabled', 'disabled');
    $('#GuidStringOfApprover6').attr('disabled', 'disabled');
}

function JERoutingEnableAllControls() {
    //$('#JERoutingSaveButton').show();
    $('#CustomizeCheckbox').removeAttr('disabled');
    $('#GuidStringOfApproverSequence').removeAttr('disabled');
    $('#GuidStringOfPreparer').removeAttr('disabled');
    $('#GuidStringOfApprover1').removeAttr('disabled');
    $('#GuidStringOfApprover2').removeAttr('disabled');
    $('#GuidStringOfApprover3').removeAttr('disabled');
    $('#GuidStringOfApprover4').removeAttr('disabled');
    $('#GuidStringOfApprover5').removeAttr('disabled');
    $('#GuidStringOfApprover6').removeAttr('disabled');
}
